package mx.netbrain.dao;

import java.util.List;

import mx.netbrain.model.Storage;
import mx.netbrain.util.HibernateUtil;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class StorageDao extends HibernateUtil {

	private SessionFactory sf = HibernateUtil.getSessionFactory();
	private Transaction t = null;
	private static final Logger logger = Logger.getLogger(StorageDao.class);

	public Storage add(Storage storage) {
		Session session = sf.openSession();
		t = session.beginTransaction();
		session.saveOrUpdate(storage);
		t.commit();
		return storage;
	}

	public Storage delete(Integer id) {
		Session session = sf.openSession();
		t = session.beginTransaction();
		Storage storage = (Storage) session.load(Storage.class, id);
		if (null != storage) {
			session.delete(storage);
		}
		t.commit();
		return storage;
	}

	@SuppressWarnings("unchecked")
	public List<Storage> list() {
		Session session = sf.openSession();
		t = session.beginTransaction();
		List<Storage> storage = null;
		try {
			storage = session.createQuery(
					"from Storage as storage where storage.status.id = 1")
					.list();
		} catch (HibernateException e) {
			logger.error("Problema con Hibernate: " + e);
			e.printStackTrace();
			t.rollback();
		}
		t.commit();
		return storage;
	}

	public Storage findById(Integer id) {
		Session session = sf.openSession();
		t = session.beginTransaction();
		Storage storage = (Storage) session.load(Storage.class, id);
		t.commit();
		return storage;
	}

}
